import { addNum, mulNum, subNum, isEmpty, mask } from 'shiptools'
import dayjs from 'dayjs'
import { 
  getLineByVoyageNoApi, 
  getLineConfigApi, 
  getChanlvConfigApi, 
  getPassengersApi, 
  getPassengerTypeConfApi, 
  getRefundDescApi, 
  createOrderApi,
  getServiceNoticeApi,
  getUnRealNameConfApi,
  getRoundTripDiscountPriceApi,
  verifyConnectTimeApi,
  getInsuranceConfigApi,
  getReserRuleApi,
  getReservationRuleApi,
  getInvoiceDetailNewApi
} from '../../api/index'

import { Logger, getAgeInt, asyncToast, showDayName, queryString, getBirthAndSex, calculateAlterTime, setPage, setEvent } from '../../utils/index'
import { 
  channel,
  SHIP_PASSENGER_TYPE, 
  SHIP_CERT_TYPE, 
  SHIP_PASSENGER_TYPE_BEIHAI, 
  CAR_NO_DEFAULT, 
  APPROVE_DESC, 
  SHIP_REG, 
  SHIP_SERVICE_TAG_DEFAULT,
  WEEK_ENUM,
  CHECK_ORDERLIST_SECONDS,
  SHIP_SERVICE_AGREEMENT_HTML,
  CERT_REG,
  TRACER_PAGES,
  PRODUCT_CODE,
  SHIP_PASSENGER_TYPE_ORDER
} from '../../utils/constants'
import { STORAGE_KEY } from '../../utils/storage'
import { buildForm, compareForm  } from '../../utils/changlv'
import { ticketTypeBuilder, checkBeiHaiTicket } from './main'
const logger = new Logger()
const pageName = TRACER_PAGES['booking']

Page({

  /**
   * 页面的初始数据
   */
  data: {

    support: {
      car: false,
      truck: false
    },
    isCarSelected: false,
    ticketCard: {
      title: '',
      seat: '',
      rule: ''
    },
    returnTicketCard: {
      title: ''
    },
    departureInfo: {
      date: '',
      departureTime: '',
      arrivalTime: '',
      departurePort: '',
      arrivalPort: '',
      shipName: '',
      seatClass: ''
    },

    backTripInfo: {
      date: '',
      departureTime: '',
      arrivalTime: '',
      departurePort: '',
      arrivalPort: '',
      shipName: '',
      seatClass: '',
    },

    isRoundTrip: false,

    truckInfo: {},
  
    currentSeat: {},
    startLine: {},
    lineConfig: {},

    // 购票须知
    serviceNoticeOpen: false,
    currentNotice: {},
    serviceNotices: [],
    defaultServiceTags: SHIP_SERVICE_TAG_DEFAULT,


    // 常旅相关
    passengers: [],
    displayPassengers: [],
    selectedPassengers: [],
    showMore: false,
    currentPassenger: {},
    carryChildModalShow: true,
    selectedIds: [],

    realNameAdultCount: 1,
    realNameChildCount: 0,
    realNameStudentCount: 0,
    realNameOldCount: 0,

    // 非实名制配置
    nonRealNameConf: {},
    realNameCert: {},
    realNameConcatName: '',
    realNameCertNo: '',
    nonRealCertIndex: 0,



    // 票种弹框
    passengerTypeConf: {},
    ticketTypeLayoutOpen: false,
    shipPassengerType: SHIP_PASSENGER_TYPE,
    shipCertType: SHIP_CERT_TYPE,

    // 去编辑 弹框
    showGoEditModal: false,

    // 车辆上船相关
    carInsuranceInfo: {},
    currentCarInsurance: {},
    currentCar: {},
    currentCarIns: {},
    vehicleInsurances: [],
    currentCarIndex: 0,

    carCode: CAR_NO_DEFAULT,

    carryPassenger: {},


    // 机场线相关
    
    // 航班日期
    airLineDepartureDate: '',

    // 航班时间
    airLineDepartureTime: '',

    airLineName: '',
    flightNumber: '',

    // 价格列表
    priceList: [],
    orderAmount: 0,

    // 购票须知、服务协议、及其他须知 枚举
    isApproveChecked: true,
    approveCates: [1],
    approveDesc: APPROVE_DESC,

    
    // 通用弹框对象
    modal: {
      open: false,

      // 标题
      title: '',

      // 主文本
      content: '',

      // 副文本
      subContent: '',

      // 取消文案
      cancel: '',

      // 确认 文案
      confirm: '',

      // 确认 confirm 的回调函数
      fn: () => {},
      
      cancelFn: () => {}
    },


    // 确认订购单弹框
    isCheckOrderListOpen: false,
    checkOrderList: [{
        id: 1,
        title: '请核对您的船票信息',
        items: []
    },{
        id: 3,
        title: '请核对乘船人信息',
        items: []
    }],

    isPriceLayoutOpened: false,


    isTicketDetailOpened: false,

    priceDetailList: [],

    // 温馨提示
    remindChecked: false,

    // 确认删除已选中常旅
    isOpenedDelModal: false,
    curerntRemoveId: '',

    // 支付弹框
    totalAmount: 0,
    isOpenedPayModal: false,
    payargs: {
      fee: 1,
      paymentArgs: {
        serialId: ''
      }
    },


    // 下单失败弹框数据
    showWarnModal: false,

    // 下单失败 错误码
    errorCode: '0',

    // 下单失败通用 弹框 对象
    warnModal: {
        title: '',
        confirmText: '',
        cancelText: '',
        showCancel: false,
        desc: ''
    },

    
    ticketTypePickerPassengers: {
      name: '',
      passenger: {},
      ticketTypeDesc: '',
      title: ``,
      list: []
    }, 
    ticketTypeChoose: false,

    selectedPassengers: [],

    selectedCarry: [],

    reservationRule: null,

    // 预约票默认 勾选
    isAlterNativeTimeOpen: false,
    ticketOutDate: '',
    backUpTime: '',
    showReserveNotice: true,
    invoiceSubtitle: '',
    supplierInfo: {},

    vstValue: ''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      query: options
    })
    this.init(options)
  },

  onShow: function() {
    const that = this
    const settings = this.data.settings
    const startLine = this.data.startLine
    const lineConfig = this.data.lineConfig
    
    const afterRemove = wx.getStorageSync('after_remove')
    const afterCreate = wx.getStorageSync('after_create')
    debugger
    if(afterRemove || afterCreate) {
      wx.removeStorageSync('after_remove')
      wx.removeStorageSync('after_create')
      const selectedIds = wx.getStorageSync(STORAGE_KEY.selectedIds)
      if(settings && startLine && lineConfig) {
        if(selectedIds) {
          wx.removeStorageSync(STORAGE_KEY.selectedIds)
          const _selectedIds = selectedIds.split('|')
          that.setData({
            selectedIds: _selectedIds
          }, () => {
            that.getPassengers(settings, startLine)
          })
        } else {
          that.getPassengers(settings, startLine)
        }
      }
    }

    
    const query = this.data.query
    setPage(pageName + '?' + queryString(query), PRODUCT_CODE)
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    wx.removeStorageSync('ship_truck_info')
  },

  onError: function (err) {
    setEvent('订单填写页', 'DD40', '^名称:'+err+'^')
  },
    
  init: function(options) {
    const that = this

    // 获取货车的缓存， 从1.5页面过来  有则默认选中
    const isCarSelected = options.car === '1'
    that.setData({
      isCarSelected
    })

    const seatId = options.seatId
    const returnSeatId = options.returnSeatId
    const voyageSerialNo = options.voyageSerialNo
    const returnNo = options.returnNo
    if(returnSeatId) {
      that.getLineById(options.voyageSerialNo).then(voyage => {
        if(!voyage) {
          return
        }
        that.getLineById(options.returnNo).then(returnVoyage => {
          if(!returnVoyage) {
            return
          }

          const selectSeat = voyage.ShipSeats.filter(item => `${item.SeatType}-${item.SeatId}-${item.DisplayName}` === decodeURIComponent(seatId))
          const selectReturnSeat = returnVoyage.ShipSeats.filter(item => `${item.SeatType}-${item.SeatId}-${item.DisplayName}` === decodeURIComponent(returnSeatId))
          if(selectSeat.length > 0 && selectReturnSeat.length > 0) {
              const voyaSeat = selectSeat[0]
              const voyaReturnSeat = selectReturnSeat[0]
              getRoundTripDiscountPriceApi({
                GoParam:{
                  ShipVoyageSerialNo: voyageSerialNo,
                  SeatId: seatId.split('-')[1],
                  SeatType: seatId.split('-')[0],
                  SeatName: voyaSeat.SeatName 
                },
                BackParam:{
                    ShipVoyageSerialNo: returnNo,
                    SeatId: returnSeatId.split('-')[1],
                    SeatType: returnSeatId.split('-')[0],
                    SeatName: voyaReturnSeat.SeatName
                },
                Channel: channel
              }).then((roundTripRes) => {
                let roundDiscount = {
                    adult: addNum(voyaSeat.SeatPrice, voyaReturnSeat.SeatPrice),
                    children: addNum(voyaSeat.ChildSeatPrice, voyaReturnSeat.ChildSeatPrice),
                    student: addNum(voyaSeat.StudentPrice, voyaReturnSeat.StudentPrice),
                    old: addNum(voyaSeat.OldSeatPrice, voyaReturnSeat.OldSeatPrice)
                }
                if(roundTripRes && roundTripRes.seatTypePriceInfos) {
                    // const roundDiscountAdult = _filter(roundTripRes.seatTypePriceInfos, item => item.TicketType === 1)
                    roundTripRes.seatTypePriceInfos.map(item => {
                        if(item.TicketType === 1) {
                            roundDiscount.adult = item.TicketPrice
                        }
                        if(item.TicketType === 2) {
                            roundDiscount.children = item.TicketPrice
                        }
                        if(item.TicketType === 3) {
                            roundDiscount.old = item.TicketPrice
                        }
                        if(item.TicketType === 4) {
                            roundDiscount.student = item.TicketPrice
                        }
                    })
                }
                            
                let currentSeat = that._getCurrentSeat(voyage, seatId)
                let currentReturnSeat = that._getCurrentSeat(returnVoyage, returnSeatId)
                
                currentSeat.SeatPrice = roundDiscount.adult
                currentSeat.ChildSeatPrice = roundDiscount.children
                currentSeat.OldSeatPrice = roundDiscount.old
                currentSeat.StudentPrice = roundDiscount.student
                that.getLineConfig(voyage, currentSeat)
                
                  
                let backTripInfo = {}
                if(!isEmpty(returnVoyage) && currentReturnSeat) {
                    backTripInfo = {
                        date: dayjs(returnVoyage.DepartDateTime).format('YYYY-MM-DD'),
                        departureTime: dayjs(returnVoyage.DepartDateTime).format('HH:mm'),
                        arrivalTime: dayjs(returnVoyage.ArriveDateTime).format('HH:mm'),
                        departurePort: returnVoyage.DepartPort,
                        arrivalPort: returnVoyage.ArrivePort,
                        shipName: returnVoyage.ShipName,
                        seatClass: currentReturnSeat.DisplayName
                    }
                }
                

                const startDate = dayjs(returnVoyage.DepartDateTime).format('MM-DD')
                const startTime = dayjs(returnVoyage.DepartDateTime).format('HH:mm')
                const dayName = returnVoyage.IsSerialVoyage? '': showDayName(returnVoyage.DepartDateTime)
                let returnTicketCard = {
                  title: `${startDate} ${dayName} ${startTime}`
                }

                that.setData({
                  backTripInfo,
                  returnTicketCard,
                  isRoundTrip: !!returnVoyage,
                  startLine: voyage,
                  returnVoyage
                })
            }).catch(err => {
                let roundDiscount = {
                    adult: addNum(voyaSeat.SeatPrice, voyaReturnSeat.SeatPrice),
                    children: addNum(voyaSeat.ChildSeatPrice, voyaReturnSeat.ChildSeatPrice),
                    student: addNum(voyaSeat.StudentPrice, voyaReturnSeat.StudentPrice),
                    old: addNum(voyaSeat.OldSeatPrice, voyaReturnSeat.OldSeatPrice)
                }

                if(!voyage || !returnVoyage) return
                          
                let currentSeat = that._getCurrentSeat(voyage, seatId)
                let currentReturnSeat = that._getCurrentSeat(returnVoyage, returnSeatId)
                currentSeat.SeatPrice = roundDiscount.adult
                currentSeat.ChildSeatPrice = roundDiscount.children
                currentSeat.OldSeatPrice = roundDiscount.old
                currentSeat.StudentPrice = roundDiscount.student
                that.getLineConfig(voyage)

                let backTripInfo = {}
                if(!isEmpty(returnVoyage) && currentReturnSeat) {
                    backTripInfo = {
                        date: dayjs(returnVoyage.DepartDateTime).format('YYYY-MM-DD'),
                        departureTime: dayjs(returnVoyage.DepartDateTime).format('HH:mm'),
                        arrivalTime: dayjs(returnVoyage.ArriveDateTime).format('HH:mm'),
                        departurePort: returnVoyage.DepartPort,
                        arrivalPort: returnVoyage.ArrivePort,
                        shipName: returnVoyage.ShipName,
                        seatClass: currentReturnSeat.DisplayName
                    }
                }
      
                const startDate = dayjs(returnVoyage.DepartDateTime).format('YYYY-MM-DD')
                const dayName = returnVoyage.IsSerialVoyage? '': showDayName(returnVoyage.DepartDateTime)
                let returnTicketCard = {
                  title: `${startDate} ${dayName}`
                }
                that.setData({
                  backTripInfo,
                  returnTicketCard,
                  isRoundTrip: !!returnVoyage,
                  startLine: voyage,
                  returnVoyage
                })
            })
          }



        })
      })
      return
    }

    // 获取班次详情  
    that.getLineById(options.voyageSerialNo).then(startLine => {
      if(!startLine) return
      const currentSeat = that._getCurrentSeat(startLine, seatId)
      that.getLineConfig(startLine, currentSeat)

      that.setData({
        startLine
      })
    })
  },

  // 跳转常旅列表
  goPassengersPage: function() {
    const that = this
    const settings = this.data.settings
    const passengers = this.data.passengers
    const { LineId, SupplierId, VoyageCabinId } = this.data.startLine
    const { OrderCountLimit, SupportChildTicket, SupportOldTicker, SupportCarryChild } = this.data.lineConfig
    const currentSeat = this.data.currentSeat

    const vstValue = this.data.vstValue
    
    const supportChild = SupportChildTicket && currentSeat.ChildSeatPrice > 0
    const supportOld = SupportOldTicker && currentSeat.OldSeatPrice > 0

    const selectedPassengers = passengers.filter(item => item.isSelected && item.id)

    let selectedIds = []
    selectedPassengers.forEach(item => selectedIds.push(`${item.id}-${item.linkerType}`))

    const param = {

      selectedIds: selectedIds.join('|'),
      lineId: LineId,
      supplierId: SupplierId,
      limit: OrderCountLimit,

      seatPrice: currentSeat.SeatPrice,
      childSeatPrice: currentSeat.ChildSeatPrice,
      displayName: currentSeat.DisplayName,
      oldSeatPrice: currentSeat.OldSeatPrice,
      citizenChildSeatPrice: currentSeat.CitizenChildSeatPrice,
      citizenSeatPrice: currentSeat.CitizenSeatPrice,
      ticketLeft: currentSeat.TicketLeft,
      supportChild: supportChild? 1: 0,
      supportOld: supportOld? 1: 0,
      supportCarry: SupportCarryChild? 1: 0,

      voyageCabinId: VoyageCabinId,
    }

    const query = queryString(param)

    setEvent('订单填写页', 'DD02', vstValue)

    if(!LineId) return

    if(passengers.length <= 0) {
      wx.navigateTo({
        url: `../create/index?${query}`,
        events: {
          createPassengerChannel: function({data}) {
            const _selectedIds = wx.getStorageSync(STORAGE_KEY.selectedIds)
            if(_selectedIds) {
              wx.removeStorageSync(STORAGE_KEY.selectedIds)
              const __selectedIds = _selectedIds.split('|')
              that.setData({
                selectedIds: __selectedIds
              }, () => {
                that.getPassengers(settings, {
                  LineId,
                  SupplierId
                }, data)
              })
            }
          }
        },
        complete: function() {
        }
      })
      return
    }
    wx.navigateTo({
      url: `../passengers/index?${query}`,
      events: {
        selectPassengersChannel: function({data}) {
            that._setPassengersMore(data)
        }
      }
    })
  },

  // 停留时间过长，重新获取班次数据
  cacheIvalidResetPage: function() {
    asyncToast({
      title: '停留时间过长，重新获取班次数据',
      icon: 'none',
      duration: 2000
    })
    .then(() => wx.navigateBack({
        delta: 2
    }))
  },

  
  getLineById: function(voyageSerialNo) {
    const that = this
    return getLineByVoyageNoApi({
      voyageSerialNo
    }).then(response => {

      if(!response || response.status !== 200) {
        return
      }
      if(!response.data || response.data.Code !== 10000) {
        logger.warn('停留太久..')
        
        wx.navigateBack({
          delta: 2
        });
        return
      }

      // 设置去程nav标题
      const startLine = response.data.Data

      if(!startLine) {
        return
      }
      

      return startLine

    }).catch(error => {
      logger.warn(error)
    })
  },

  // 获取班次配置信息
  getLineConfig: function(startLine, currentSeat) {
    const that = this
    getLineConfigApi({
      LineId: startLine.LineId,
      DepartDate: startLine.DepartDateTime,
      Channel: channel
    }).then(response => {
      if(!response || response.status !== 200) {
        return
      }
      if(!response.data || response.data.Code !== 10000) {
        logger.warn('停留太久..')
        return
      }
      const lineConfig = response.data.Data

      
      that.getChanglvConfig(startLine, lineConfig)

      that.getInsuranceConfig(startLine, lineConfig)

      that.getServiceNotice(startLine, lineConfig)


      that.getInvoiceDetail(startLine)

      // 预约票
      const reservationRule = this.data.reservationRule
      const isRoundTrip = this.data.isRoundTrip
      if(startLine.IsReseverVoyage && !reservationRule && !isRoundTrip) {
        that.getReserRule({
            LineId: startLine.LineId,
            SupplierId: startLine.SupplierId,
            DepartDate: dayjs(startLine.DepartDateTime).format('YYYY-MM-DD')
        }).then(data => {

          if(!data.status || data.status !== 200) {
            return
          }

          const result = data.data
          if(!result || result.Code !== 10000) {
            return
          }
          const reservationRule = result.Data
            
          const isAlterNativeTimeOpen = reservationRule.AlternativeStatus === 1 && reservationRule.DefaultSelected
          const ticketOutDate = dayjs(startLine.DepartDateTime).add(mulNum(subNum(startLine.PreSaleDays, 1, startLine.ReserveDays), -1), 'day').format('MM月DD日')
          const alternativeTimeType = Number(reservationRule.AlternativeTime)
          let backUpTime=  calculateAlterTime(alternativeTimeType, startLine.DepartDateTime)
          that.setData({
            isAlterNativeTimeOpen,
            ticketOutDate,
            backUpTime,
            reservationRule
          })
            // 预约票出票提示
            // if (!data || data.AlternativeStatus !== 1) {
            //     self.openReserveTicketNotice()
            // }
            // self.setAlternativeTimeData(voyage, data)
        })
    }

      // 设置顶部信息
      that.setTicketInfo(startLine, lineConfig, currentSeat)


    })
  },

  getPassengerTypeConf: function({LineId}) {
    const that = this
    return getPassengerTypeConfApi({LineId}).then(response => {
      that.setData({
        passengerTypeConf: response
      })
      return response
    })
  },

  getChanglvConfig: function(startLine, lineConfig) {
    const that = this
    const {LineId, SupplierId} = startLine
    const { IsRealName } = lineConfig
    
    if(!IsRealName) {

      that.getUnRealNameConf(LineId).then((nonRealNameConf) => {
        const defaultPassengers = [{
          birthday: "",
          channel: null,
          email: null,
          englishMing: null,
          englishXin: null,
          fromChannel: 0,
          id: "20599163601400000",
          isDefault: 1,
          issueDate: "",
          issueNum: 0,
          linkerName: "",
          linkerType: 0,
          listNos: [],
          memberId: "",
          mobile: null,
          nationalCode: null,
          nationality: "",
          nationalityDetail: "",
          nationalityThreeCode: "",
          nationalityTwoCode: "",
          openId: null,
          overSeasMobilephone: "",
          personal: 0,
          phone: null,
          platformId: 1,
          products: "30",
          sex: 1,
          shipLinkerId: 0,
          shipMemberId: null,
          unionId: null,
          visaDate: "",
          isSelected: true
        }]
        this.setData({
          nonRealNameConf,
          passengers: defaultPassengers
        }, () => {
          that.priceCalculation()
        })
      })

      return
    }
    getChanlvConfigApi({ LineId }).then(response => {
      const formItems = buildForm(false, response, SupplierId, {})
      this.setData({
        settings: response
      })
      that.getPassengers(response, startLine)
    })
  },

  getPassengers: function(settings, startLine, createP) {
    const that = this
    const showMore = this.data.showMore
    const { SupplierId  } = startLine
    const openId = wx.getStorageSync(STORAGE_KEY.openId)
    const unionId = wx.getStorageSync(STORAGE_KEY.unionId)
    const memberId = wx.getStorageSync(STORAGE_KEY.memberId)
    wx.showLoading({
      title: '正在加载...',
      mask: true,
    });
    let selectedIds = that.data.selectedIds
    getPassengersApi({
      TCMemberId: memberId,
      OpenId: openId,
      UnionId: unionId,
      Channel: channel,
      PageIndex: 1,
      PageSize: 999,
      ShipMemberId: ''
    }).then(response => {
      wx.hideLoading();
      if(!response || response.length <= 0) {
        that._setPassengersMore([])
        return
      }
      let passengers = []
      response.forEach(item => {
        const { passenger, invalidMsg } = compareForm(item, settings, SupplierId, false)
        if(createP && createP.id) {
          selectedIds.push(`${createP.id}-${createP.linkerType}`)
        }
        const _selectedIds = selectedIds.join('|')
        passenger.isSelected = _selectedIds.includes(`${item.id}`)

        passenger.linkerType = 0
        if(selectedIds && selectedIds.length > 0) {
          selectedIds.forEach(idType => {
            if(idType.includes(item.id)) {
              const type = idType.split('-')[1]
              passenger.linkerType = type

              // 编辑回来的逻辑
              if(createP && createP.id === item.id) {
                passenger.linkerType = createP.linkerType
              }
            }
          })
        }
        passengers.push(passenger)
      })
        
      that._setPassengersMore(passengers)
    })
  },

  
  // 获取车辆保险
  getInsuranceConfig: function(startLine, lineConfig) {
    const that = this
    const { DepartDateTime, ArrivePort, DepartPort, LineId, ShipCode, SupplierId } = startLine

    getInsuranceConfigApi({
      ArrivePort,
      Channel: channel,
      DepartPort,
      DepartTime: DepartDateTime,

      // FIXME: refid 需要修改成腾讯出行船票插件端的 refid
      FromRefId: "464341607",
      LineId,
      ShipCode,
      SupplierId
    }).then(response => {
      if(!response || response.status !== 200) {
        return
      }
      if(!response.data || response.data.code !== 10000) {
          return
      }
      const carInsuranceInfo = response.data.data
      let currentCarInsurance = {}
      let currentCar = {}
      let isSoldOut = true
      // 过滤余票
      if(carInsuranceInfo.vehicleList && carInsuranceInfo.vehicleList.length > 0) {
        carInsuranceInfo.vehicleList = carInsuranceInfo.vehicleList.filter(item => {
            if(item.vehicleTicketLeft > 0) {
                item.name = `${item.vehicleTypeName}  ￥${item.vehicleTicketPrice}`
                return item
            }
        })
      }
      if(carInsuranceInfo.vehicleList.length > 0) {
          isSoldOut = false
      }
      if(carInsuranceInfo.vehicleList && carInsuranceInfo.vehicleList.length > 0) {
          currentCar = carInsuranceInfo.vehicleList[0]
      }

      let vehicleInsurances = carInsuranceInfo.vehicleInsurance && carInsuranceInfo.vehicleInsurance.vehicleInsurances || []

      let _insurances = []
      if(carInsuranceInfo.vehicleInsurance && vehicleInsurances && vehicleInsurances.length > 0) {
        let emptyInsurance = null
        let defaultInsurance = null
        carInsuranceInfo.vehicleInsurance.vehicleInsurances.forEach(item => {
            if(item.insuranceId === 0) {
                emptyInsurance = item
            } else {
                if(item.isDefault === 1) {
                    defaultInsurance = item
                } else {
                    _insurances.push(item)
                }
            }
        })

        // 默认保险排序第一个
        if(defaultInsurance) {
            _insurances.unshift(defaultInsurance)
        }

        // 默认不购买保险排序最后
        if(emptyInsurance) {
            _insurances.push(emptyInsurance)
        }

        carInsuranceInfo.vehicleInsurance.vehicleInsurances = _insurances
        
        const filterCurrCars = carInsuranceInfo.vehicleInsurance.vehicleInsurances.filter(item => item.isDefault === 1)
        if(filterCurrCars && filterCurrCars.length > 0 && isEmpty(currentCarInsurance)) {
          currentCarInsurance = filterCurrCars[0]
        }
      
      }

      // 计算最终价格
      that.setData({
        carInsuranceInfo: carInsuranceInfo,
        currentCarInsurance,
        currentCar,
        vehicleInsurances: _insurances
      }, () => {
        
      })

    })
  },


  // 非实名制配置
  getUnRealNameConf: function(lineId) {
    return getUnRealNameConfApi({
      lineId
    }).then(response => response)
  },
  

  getRefundDesc: function(startLine, lineConfig, seat) {
    const that = this
    getRefundDescApi({
      Date: startLine.DepartDateTime,
      LineId: startLine.LineId,
      supplierId: startLine.SupplierId,
      SeatId: seat.SeatId,
      SeatName: seat.SeatName
    }).then(response => {
      let ticketCard = this.data.ticketCard
      ticketCard.rule = response.Description
      that.setData({
        ticketCard
      })
    })
  },

  // 获取购票须知
  getServiceNotice: function(startLine, lineConfig) {
    const that = this
    const { LineId, DepartDateTime } = startLine
    getServiceNoticeApi({
      LineId,
      DepartDate: DepartDateTime,
      SeatName:""
    }).then(response => {
      if(!response || response.length <= 0) {
        return
      }
      
      that.setData({
        serviceNotices: response
      })
    })
  },


  closeLineService: function() {
    this.setData({
      serviceNoticeOpen: false    
    })
  },
  
  onServiceNotice: function(e) {
    
    let item = e.detail
    if(!item || !item.NoticeType) {
      const serviceNotices = this.data.serviceNotices
      if(!serviceNotices || serviceNotices.length <= 0) return
      item = serviceNotices[0]
      
    }

    this.setData({
      serviceNoticeOpen: true,
      currentNotice: item
    })
    const vstValue = this.data.vstValue
    setEvent('订单填写页', 'DD01', vstValue)
  },

  _setPassengersMore: function(passengers) {
    const that = this
    const showMore = this.data.showMore
    const targetIndex = showMore? passengers.length: passengers.length > 8? 7: passengers.length

    if(passengers.length <= 0) {
      that.setData({
        passengers: [],
        selectedIds: [],
        selectedPassengers: []
      }, () => {
        that.priceCalculation()
      })
      return
    }
    passengers.forEach((item, index) => {
      item.show = false
      if(index < targetIndex) {
        item.show = true
      }
    })
    const selectedPassengersAfter = that._selectedPasssengers(passengers)
    const selectedIds = selectedPassengersAfter.map(item => `${item.id}-${item.linkerType}`)
    that.setData({
      passengers,
      selectedIds
    }, () => {
      that.priceCalculation()
    })
  },

  _getCurrentSeat: function(voyage, seatId) {

    if(!voyage) {
      logger.warn(`停留太久，班次过期了，回到列表页重新选择`)
      return
    }

    const selectSeat = voyage.ShipSeats.filter(item => `${item.SeatType}-${item.SeatId}-${item.DisplayName}` === decodeURIComponent(seatId))
    if (!selectSeat || selectSeat.length === 0) {
      return {}
    }

    return selectSeat[0]
  },

  setTicketInfo: function(startLine, lineConfig, currentSeat) {
    const that = this
    const isRoundTrip = this.data.isRoundTrip
    const support = {
      children: lineConfig.SupportChildTicket && currentSeat.ChildSeatPrice  > 0,
      old: lineConfig.SupportOldTicker && currentSeat.OldSeatPrice  > 0,

      // FIXME: 暂不支持学生票
      // student: lineConfig.SupportStudentTicket && currentSeat.StudentPrice  > 0,
      student: false,
      carryChild: lineConfig.SupportCarryChild,
      car: lineConfig.SupportVehicle,
      isRealName: lineConfig.IsRealName,
      truck: startLine.SupportHuoche === 1,
      airline: lineConfig.IsArriveAirPort && !isRoundTrip,
      isSerial: startLine.IsSerialVoyage
    }

    if(support.airline) {
      setEvent('订单填写页', 'DD38', '')
    }

    const startDate = dayjs(startLine.DepartDateTime).format('MM-DD')
    const startTime = dayjs(startLine.DepartDateTime).format('HH:mm')
    const dayName = support.isSerial? '': showDayName(startLine.DepartDateTime, !isRoundTrip)

    const adult = `¥${currentSeat.SeatPrice}/成人票`
    const children = support.children? `¥${currentSeat.ChildSeatPrice}/儿童票`: ''
    const student = support.student? `¥${currentSeat.StudentPrice}/学生票`: ''
    const old = support.old? `¥${currentSeat.OldSeatPrice}/长者票`: ''
    const carryChild = support.carryChild? `免费/携童`: ''

    const serviceFee = addNum(lineConfig.LineServiceFee, lineConfig.TCLineServiceFee, lineConfig.Discount)
    const serviceFeeTxt = serviceFee > 0? `¥${serviceFee}/服务费`: ''
    
    let ticketCard = {
      title: `${startDate} ${dayName} ${startTime}`,
      seat: currentSeat.DisplayName,
      price: `${adult} ${children} ${student} ${old} ${carryChild} ${serviceFeeTxt}`
    }
    
    // 获取退改须知
    that.getRefundDesc(startLine, lineConfig, currentSeat)


    // 初始化同意勾选
    let approveDefault = lineConfig.IsExemption === 1

    let departureInfo = {
      date: dayjs(startLine.DepartDateTime).format('YYYY-MM-DD'),
      departureTime: dayjs(startLine.DepartDateTime).format('HH:mm'),
      arrivalTime: dayjs(startLine.ArriveDateTime).format('HH:mm'),
      departurePort: startLine.DepartPort,
      arrivalPort: startLine.ArrivePort,
      shipName: startLine.ShipName,
      seatClass: currentSeat.DisplayName
    }
    

    let remindChecked = lineConfig.LineRemind.length < 160

    const phoneNumber = wx.getStorageSync(STORAGE_KEY.mobile) || ''
    const emailStr = wx.getStorageSync(STORAGE_KEY.email) || ''
    const carCode = wx.getStorageSync(STORAGE_KEY.carLicense) || CAR_NO_DEFAULT

    const vstValue = `^港口航线:${startLine.DepartPort}-${startLine.ArrivePort}^航线名称:${startLine.DepartCity}-${startLine.ArriveCity}`
    
    that.setData({
      support,
      departureInfo,
      currentSeat,
      startLine,
      lineConfig,
      ticketCard,
      phoneNumber,
      emailStr,
      carCode,
      isApproveChecked: approveDefault,
      remindChecked,
      vstValue
    }, () => {
      that.getPassengerTypeConf(startLine).then((passengerTypeConf) => {
        const priceDesc = [adult,children, student, old, carryChild, serviceFeeTxt]
        const priceDetailList = that.getPriceDetailList(priceDesc, startLine, passengerTypeConf)
        that.setData({
          priceDetailList
        })

      })
    })
  },

  _selectedPasssengers: function(passengers) {

    const { SupportChildTicket, SupportCarryChild } = this.data.lineConfig
    const selectedCarry = this.data.selectedCarry
    const carryIds = selectedCarry.map(item => item.id)

    let selectedP = []
    passengers.forEach(item => {
      item.showCarryForm = false
      
      item.supportChild = SupportChildTicket
      item.supportCarryChild = SupportCarryChild && ![1, 24].includes(Number(item.linkerType))
      if(carryIds.includes(item.id) && item.supportCarryChild) {
        item.showCarryForm = true
      }

      if(item.isSelected) {
        selectedP.push(item)
      }
    })
    return selectedP
  },
  
  onChoosePassenger: function(e) {
    const that = this
    const item = e.currentTarget.dataset.item
    const { OrderCountLimit } = that.data.lineConfig
   
   
    const { SupportChildTicket, SupportCarryChild } = this.data.lineConfig

    const passengers = this.data.passengers

    const selectedPassengers = that._selectedPasssengers(passengers)
    const { passenger, ticketTypeChoose, ticketTypePickerPassengers } = that.doPassengerType(item)

    setEvent('订单填写页', 'DD29', '')

    if(OrderCountLimit <= selectedPassengers.length && !passenger.isSelected) {
      wx.showToast({
        title: `最多只能添加${OrderCountLimit}位乘客`,
        icon: 'none'
      })
      return
    }

    if(!item.isValid) {
      logger.warn(`${item.showName}: 校验不通过`)
      that.showModalEdit(item)
      return
    }

    if(ticketTypeChoose && !passenger.isSelected) {
      that.showPassengerTypeLayout()
      return
    }

    passengers.forEach(p => {
      if(passenger.id === p.id) {
        p.linkerType = passenger.linkerType
        p.isSelected = !p.isSelected
        p.supportChild = SupportChildTicket
        p.supportCarryChild = SupportCarryChild && ![1, 24].includes(item.linkerType)
        p.showCarryForm = false
      }
    })

    const selectedPassengersAfter = that._selectedPasssengers(passengers)
    const selectedIds = selectedPassengersAfter.map(item => `${item.id}-${item.linkerType}`)

    this.setData({
      passengers,
      selectedIds
    }, () => {
      that.priceCalculation()
    })
  },

  onMorePassengers: function() {
    let passengers = this.data.passengers
    const showMore = this.data.showMore

    const targetIndex = !showMore? passengers.length: 7
    passengers.forEach((item, index) => {
      item.show = false
      if(index < targetIndex) {
        item.show = true
      }
    })
    this.setData({
      showMore: !showMore,
      passengers
    })
  },

  onRemovePassenger: function(e) {
    const that = this
    const item = e.currentTarget.dataset.item

    this.setData({
      isOpenedDelModal: true,
      curerntRemoveId: item.id
    })

    const vstValue = this.data.vstValue
    setEvent('订单填写页', 'DD03', vstValue)
  },


  handleDelClose() {
    this.setData({
      isOpenedDelModal: false
    })
  },
  handleDelCancel() {
    this.setData({
      isOpenedDelModal: false
    })
  },
  handleDelConfirm() {
    const that = this
    const curerntRemoveId = this.data.curerntRemoveId
    let passengers = this.data.passengers
    passengers.forEach(p => {
      if(p.id === curerntRemoveId) {
        p.isSelected = false
      }
    })
    const selectedPassengersAfter = that._selectedPasssengers(passengers)
    const selectedIds = selectedPassengersAfter.map(item => `${item.id}-${item.linkerType}`)

    this.setData({
      passengers,
      selectedIds,
      isOpenedDelModal: false,
      curerntRemoveId: ''
    }, () => {
      that.priceCalculation()
    })
  },


  onEditPassenger: function(e) {
    const that = this
    const currentPassenger = e.currentTarget.dataset.item
    const settings = this.data.settings
    const passengers = this.data.passengers
    const { LineId, SupplierId, VoyageCabinId } = this.data.startLine
    wx.setStorageSync(STORAGE_KEY.editPassenger, currentPassenger);

    const currentSeat = this.data.currentSeat
    const { OrderCountLimit, SupportChildTicket, SupportOldTicker, SupportCarryChild } = this.data.lineConfig

    const supportChild = SupportChildTicket && currentSeat.ChildSeatPrice > 0
    const supportOld = SupportOldTicker && currentSeat.OldSeatPrice > 0

    const param = {
      editId: currentPassenger.id,
      lineId: LineId,
      supplierId: SupplierId,
      limit: OrderCountLimit,

      seatPrice: currentSeat.SeatPrice,
      childSeatPrice: currentSeat.ChildSeatPrice,
      displayName: currentSeat.DisplayName,
      oldSeatPrice: currentSeat.OldSeatPrice,
      citizenChildSeatPrice: currentSeat.CitizenChildSeatPrice,
      citizenSeatPrice: currentSeat.CitizenSeatPrice,
      ticketLeft: currentSeat.TicketLeft,
      supportChild: supportChild? 1: 0,
      supportOld: supportOld? 1: 0,
      supportCarry: SupportCarryChild? 1: 0,

      voyageCabinId: VoyageCabinId,
    }

    const query = queryString(param)

    const selectedPassengers = passengers.filter(item => item.isSelected && item.id)

    let selectedIds = []
    selectedPassengers.forEach(item => selectedIds.push(`${item.id}-${item.linkerType}`))
    wx.setStorageSync(STORAGE_KEY.selectedIds, selectedIds.join('|'))
    wx.navigateTo({
      url: `../create/index?${query}`,
      events: {
        createPassengerChannel: function({data}) {
          const _selectedIds = wx.getStorageSync(STORAGE_KEY.selectedIds)
          if(_selectedIds) {
            wx.removeStorageSync(STORAGE_KEY.selectedIds)
            const __selectedIds = _selectedIds.split('|')
            that.setData({
              selectedIds: __selectedIds
            }, () => {
              that.getPassengers(settings, {
                LineId,
                SupplierId
              }, data)
            })
          }
          
        }
      },
      complete: function() {
      }
    })
  },

  showModalEdit: function(item) {
    this.setData({
      currentPassenger: item,
      showGoEditModal: true
    })
  },

  closeModal: function() {
    this.setData({
      showGoEditModal: false
    })
  },

  confirmModal: function() {
    const that = this
    const currentPassenger = that.data.currentPassenger
    const { LineId, SupplierId, VoyageCabinId } = that.data.startLine
    const settings = this.data.settings
    const currentSeat = this.data.currentSeat
    const { OrderCountLimit, SupportChildTicket, SupportOldTicker, SupportCarryChild } = this.data.lineConfig
    // 保存要编辑的常旅到 storage 
    wx.setStorageSync(STORAGE_KEY.editPassenger, currentPassenger);

    const supportChild = SupportChildTicket && currentSeat.ChildSeatPrice > 0
    const supportOld = SupportOldTicker && currentSeat.OldSeatPrice > 0
    const param = {
      editId: currentPassenger.id,
      lineId: LineId,
      supplierId: SupplierId,
      limit: OrderCountLimit,

      seatPrice: currentSeat.SeatPrice,
      childSeatPrice: currentSeat.ChildSeatPrice,
      displayName: currentSeat.DisplayName,
      oldSeatPrice: currentSeat.OldSeatPrice,
      citizenChildSeatPrice: currentSeat.CitizenChildSeatPrice,
      citizenSeatPrice: currentSeat.CitizenSeatPrice,
      ticketLeft: currentSeat.TicketLeft,
      supportChild: supportChild? 1: 0,
      supportOld: supportOld? 1: 0,
      supportCarry: SupportCarryChild? 1: 0,

      voyageCabinId: VoyageCabinId,
    }

    const query = queryString(param)

    wx.navigateTo({
      url: `../create/index?${query}`,
      events: {
        createPassengerChannel: function({data}) {
          const _selectedIds = wx.getStorageSync(STORAGE_KEY.selectedIds)
          if(_selectedIds) {
            wx.removeStorageSync(STORAGE_KEY.selectedIds)
            const __selectedIds = _selectedIds.split('|')
            that.setData({
              selectedIds: __selectedIds
            }, () => {
              that.getPassengers(settings, {
                LineId,
                SupplierId
              }, data)
            })
          }
        }
      },
      complete: function() {
        that.closeModal()
      }
    })

  },

  closeCommonModal: function() {
    
    const modal = {
      open: false,
      title: '',
      content: '',
      subContent: '',
      cancel: '',
      confirm: '',
      fn: () => {},
      cancelFn: () => {},
    }
    this.setData({modal})
  },

  confirmCommonModal: function(e) {
    this.closeCommonModal()
  },

  doPassengerType: function(p) {
    const lineConfig = this.data.lineConfig
    const seat = this.data.currentSeat
    const voyage = this.data.startLine
    const { SupportChildTicket, SupportOldTicker} = lineConfig
      
    const supportChild = SupportChildTicket && seat.ChildSeatPrice > 0
    const supportOld = SupportOldTicker && seat.OldSeatPrice > 0


    const passengerTypeConf = this.data.passengerTypeConf

    const { ticketTypePickerPassengers, ticketTypeChoose, passenger } = ticketTypeBuilder({
      passengerTypeConf,
      seat,
      p,
      supportChild,
      supportOld
    })

    this.setData({
      ticketTypePickerPassengers
    })
    return {
      passenger,
      ticketTypeChoose,
      ticketTypePickerPassengers
    }
  },

  onChooseTicketType: function(e) {
    const item = e.detail
    let ticketTypePickerPassengers = Object.assign({}, this.data.ticketTypePickerPassengers)
    
    ticketTypePickerPassengers.list.forEach(_item => {
      _item.isSelected = false
      if(item.id === _item.id) {
        _item.isSelected = true
      }
    })

    this.setData({
      ticketTypePickerPassengers
    })

    if(ticketTypePickerPassengers.passenger) {
      const _type = ticketTypePickerPassengers.passenger.linkerType
  
      setEvent('订单填写页', 'DD34', `^票型选择:${SHIP_PASSENGER_TYPE_ORDER[_type]}^`)

    }
  },

  onConfirmTciketType: function(e) {
    let ticketTypePickerPassengers = Object.assign({}, this.data.ticketTypePickerPassengers)
    const selectedTicketType = ticketTypePickerPassengers.list.filter(item => item.isSelected)[0]
    
    setEvent('订单填写页', 'DD35', '')

    if(!selectedTicketType) {
      return
    }
    const passengers = this.data.passengers

    const { passenger } = ticketTypePickerPassengers

    const currentSeat = this.data.currentSeat


    // 北海市民 校验
    const isBeiHai = [0, 1, 22, 24].includes(selectedTicketType.type) && (currentSeat.CitizenSeatPrice > 0 || currentSeat.CitizenChildSeatPrice > 0)
    if(isBeiHai) {
      const currentVoyage = this.data.startLine

      checkBeiHaiTicket({
        BelongType: SHIP_PASSENGER_TYPE_BEIHAI[selectedTicketType.type], // (1:岛民,2:市民,3:员工票,4:市民儿童,5:普通成人,6:普通儿童)
        SupplierId: currentVoyage.SupplierId,
        CertNo: passenger.id? passenger.validFirstCert.certNo: passenger.firstCertNo,
        PassengerName: passenger.linkerName,
        CarryChildCertNo: passenger.carryChildCert || '',
        VoyageCabinId: currentVoyage.VoyageCabinId || 1,
        LineId: currentVoyage.LineId,
      }, passenger.linkerType).then(response => {
        if(response) {
          this.changeTicketType(passengers, passenger, selectedTicketType)
        }
      })
      
      return
    }

    this.changeTicketType(passengers, passenger, selectedTicketType)
  },

  changeTicketType: function(passengers, passenger, selectedTicketType) {
    const that = this

    const { SupportChildTicket, SupportCarryChild } = this.data.lineConfig
    
    passengers.forEach(item => {
      if(item.id === passenger.id) {
        item.linkerType = selectedTicketType.type
        item.isSelected = !item.isSelected
        item.supportChild = SupportChildTicket
        item.supportCarryChild = SupportCarryChild && ![1, 24].includes(item.linkerType)
      }
    })

    this.closeTicketTypeLayout()
    this.setData({
      passengers
    }, () => {
      
      that.priceCalculation()
    })
  },

  closeFloatLayout: function() {
    this.setData({
      ticketTypeLayoutOpen: false
    })
  },

  showPassengerTypeLayout: function() {
    this.setData({
      ticketTypeLayoutOpen: true
    })
  },

  closeTicketTypeLayout: function() {
    this.setData({
      ticketTypeLayoutOpen: false
    })
  },

  onFocusPhone: function() {
    const vstValue = this.data.vstValue
    setEvent('订单填写页', 'DD04', vstValue)
  },

  onInputPhone: function(e) {
    const phone = e.detail
    this.setData({
      phoneNumber: phone
    })
  },
  onClearPhone: function() {
    this.setData({
      phoneNumber: ''
    })
  },

  onInputEmail: function(e) {
    const email = e.detail
    this.setData({
      emailStr: email
    })

  },  
  onClearEmail: function() {
    this.setData({
      emailStr: ''
    })
  },

  onInputCarryName: function(e) {
    const value = e.detail.value
    const item = e.currentTarget.dataset.item
    const passengers = this.data.passengers
    passengers.forEach(p => {
      if(item.id === p.id) {
        p.carryChildName = value
      }
    })

    const selectedPassengers = this._selectedPasssengers(passengers)
    this.setData({
      passengers,
      selectedPassengers
    })

  },
  
  onInputCarryCert: function(e) {
    const value = e.detail.value
    const item = e.currentTarget.dataset.item
    const passengers = this.data.passengers
    passengers.forEach(p => {
      if(item.id === p.id) {
        p.carryChildCert = value
      }
    })

    const selectedPassengers = this._selectedPasssengers(passengers)
    this.setData({
      passengers,
      selectedPassengers
    })
  },

  onInputRealNameConcat: function(e) {
    const value = e.detail
    this.setData({
      realNameConcatName: value
    })
  },
  onClearRealNameConcat: function() {
    this.setData({
      realNameConcatName: ''
    })
  },

  onCelarRealNameConcat: function() {
    this.setData({
      realNameConcatName: ''
    })
  },

  onInputRealNameCert: function(e) {
    const value = e.detail.value
    this.setData({
      realNameCertNo: value
    })
  },

  _selectCarry: function(passengers, item) {

    passengers.forEach(p => {
      if(p.id === item.id) {
        p.showCarryForm = !p.showCarryForm
      }
    })
    const selectedCarry = passengers.filter(item => item.showCarryForm)
    this.setData({
      passengers,
      selectedCarry
    })
  },
  onSelectCarryChild: function(e) {
    const that = this
    const item = e.currentTarget.dataset.item
    const startLine = this.data.startLine
    const carryChildModalShow = this.data.carryChildModalShow
    let passengers = this.data.passengers
    
    that._selectCarry(passengers, item)
    if(carryChildModalShow) {
      that.setData({
        carryChildModalShow: false,
        carryPassenger: item
      })
      this.showShipModal({
        title: '温馨提示',
        content: startLine.SupportCarryChildRemark,
        subContent: '一名成人仅可携带一名免票儿童',
        cancel: '',
        confirm: '知道了'
      })
      return
    }
    
  },

  handleSwitchChange: function(e) {
    const that = this
    this.setData({
      isCarSelected: e.detail.value
    }, () => {
      that.priceCalculation()
    })
  },

  bindPickerCarType: function(e) {
    const that = this
    const carInsuranceInfo = this.data.carInsuranceInfo
    this.setData({
      currentCarIndex: e.detail.value,
      currentCar: carInsuranceInfo.vehicleList[e.detail.value]
    }, () => {
      that.priceCalculation()
    })
  },

  
  onPlateHandler: function(e) {
    const code = e.detail
    
    this.setData({
      carCode: code
    })
    
  },

  onChangeApprove: function(e) {
    this.priceCalculation()
    const isApproveChecked = this.data.isApproveChecked
    this.setData({
      isApproveChecked: !isApproveChecked
    })

    setEvent('订单填写页', 'DD22', '')
  },

  showShipModal(data, fn, cancelFn) {
    if(!cancelFn) cancelFn = function(){}
    const modal = {
        open: true,
        title: data.title,
        content: data.content,
        subContent: data.subContent,
        cancel: data.cancel,
        confirm: data.confirm,
        fn,
        cancelFn
    }
    this.setData({
        modal
    })
  },

  // 机场线相关
  onChooseAirLines: function() {
    const that = this
    wx.navigateTo({
      url: `../airlines/index`,
      events: {
        selectAirLineChannel: function({data}) {
          that.setData({
            airLineName: data.airCName,
            flightNumber: ''
          })
        }
      }
    })

    setEvent('订单填写页', 'DD23', '')
  },
  onDateChangeHandler: function(e) {
    this.setData({
      airLineDepartureDate: e.detail
    })
    setEvent('订单填写页', 'DD24', '')
  },
  selectAirLineTime: function(e) {
    this.setData({
      airLineDepartureTime: e.detail
    })
  },
  handleFlightNumberChange: function(e) {
    this.setData({
      flightNumber: e.detail
    })
  },
  airLineNameChangeHandler: function(e) {},

  

  /**
   * 获取车辆上船 价格列表 和 下单参数
   *
   * @param {*} {carInsurance, currCar, open, carCode}
   * @returns
   * @memberof Index
   */
  getCarOnShipParam({carInsurance, currCar, currentCarIns, open, carCode, vehicleRadioValue, truckInfo}) {
    const bookingVoyage = this.data.startLine
    let carOnShip = carInsurance && currCar && currCar.vehicleTicketLeft > 0 && open
    let _priceList = []
    let carParam = {}

    // FIXME:目前不支持货车上船， 这里暂时隐藏掉
    // if(bookingVoyage.SupportHuoche === 1 && (!truckInfo || !truckInfo.current || !truckInfo.current.CarTypeID)) {
    //     carOnShip = false
    // }

    if(!carOnShip) {
        return {
            carOnShip,
            priceListTmp: [],
            param: null
        }
    }

    
    // 车辆上船下单 参数 
    let carCodeNo  = ''
    let _carCode = Object.assign([], carCode) || []
    if(_carCode) {
        carCodeNo = _carCode.shift()
    }

    let vehicle = {
        Code: currCar.vehicleTypeID,
        Type: currCar.vehicleTypeName,
        Province: carCodeNo,//归属地
        NO: carCode.join(''), //车牌号
        TicketPrice: currCar.vehicleTicketPrice,
        Length: currCar.vehicleLength,
        IsBusiness: vehicleRadioValue == 1?1:0,  // 营运车辆
        TicketPriceID: currCar.ticketPriceID,
        GradeCode: currCar.gradeCode,
    }
    
    _priceList.push({
        hidden: false,
        type: '车辆上船',
        price: vehicle.TicketPrice,
        count: 1
    })

    carParam.VehicleInfo = [vehicle]
    

    

    return {
        carOnShip,
        priceListTmp: _priceList,
        param: carParam
    }
  },


  // 下单相关
  
  /**
   * 当前选择常旅 类型 及 各类型的价格和数量， 包含了非实名制
   *
   * @param {*} {passengers, seat, isRealSys}
   * @returns
   * @memberof Index
   */
  passengerCategories({
      
    realNameAdultCount,
    realNameChildCount,
    realNameStudentCount,
    realNameOldCount,
    passengers, 
    seat, 
    isRealSys}) {

    let __selectedPassengers = Object.assign([], passengers)

    if(!__selectedPassengers || __selectedPassengers.length <= 0) {
        return {
                
            allPass: {
                price: 0,
                count: 0
            },
            adults: {
                price: 0,
                count: 0
            },
            children: {
                price: 0,
                count: 0
            },
            senior: {
                price: 0,
                count: 0
            },
            student: {
                price: 0,
                count: 0
            },
            
            citizenAdults: {
                price: 0,
                count: 0
            },
            citizenChildren: {
                price: 0,
                count: 0
            }
        }
    }
    // 成人票价
    let APrice = seat.SeatPrice
    // 儿童票价
    let CPrice = seat.ChildSeatPrice
    // 学生票价
    let SPrice = seat.StudentPrice
    // 长者票价
    let OPrice = seat.OldSeatPrice

    let ACPrice = seat.CitizenSeatPrice
    let CCPrice = seat.CitizenChildSeatPrice

    let AllCount = __selectedPassengers.length
    // 成人票数
    let ACount = __selectedPassengers.filter((p) => p.linkerType == 0).length
    // 儿童票数
    let CCount = __selectedPassengers.filter((p) => p.linkerType == 1).length
    // 学生票数
    let SCount = __selectedPassengers.filter((p) => p.linkerType == 2).length
    // 长者票数
    let OCount = __selectedPassengers.filter((p) => p.linkerType == 3).length

    // 北海市民成人数
    let ACCount = __selectedPassengers.filter((p) => p.linkerType == 22).length

    // 北海市民儿童数
    let CCCount = __selectedPassengers.filter((p) => p.linkerType == 24).length

    // 非实名制
    if(!isRealSys) {
        ACount = realNameAdultCount
        CCount = realNameChildCount
        SCount = realNameStudentCount
        OCount = realNameOldCount
        
        __selectedPassengers = this.setNoRealNamePassengers(seat, {
            realNameAdultCount: ACount,
            realNameChildCount: CCount,
            realNameStudentCount: SCount,
            realNameOldCount: OCount
        })

        AllCount = __selectedPassengers.length

    }
    return {
        allPass: {
            price: addNum(APrice, CPrice, OPrice, SPrice),
            count: AllCount
        },
        adults: {
            price: APrice,
            count: ACount
        },
        children: {
            price: CPrice,
            count: CCount
        },
        senior: {
            price: OPrice,
            count: OCount
        },
        student: {
            price: SPrice,
            count: SCount
        },
        citizenAdults: {
            price: ACPrice,
            count: ACCount
        },
        citizenChildren: {
            price: CCPrice,
            count: CCCount
        }
    }

  },

  
  setNoRealNamePassengers(seat, count) {
    const {
        realNameAdultCount,
        realNameChildCount,
        realNameStudentCount,
        realNameOldCount,
        certType,
        certNo,
        name
    } = count
    const  passengerInfoContent = (userType = 1, seatPrice) => ({
        Name: name || '',
        Sex: 0,
        passengerType: 0,
        SeatType: seat.SeatType,
        SeatName: seat.DisplayName,
        TicketPrice: seatPrice,
        SeatId: seat.SeatId,
        UserType: userType,
        IdCard: certNo || '',
        IdType: certType || 0,
        MobileNo: '',
        birthDay:'',
        passportDate: '',
        visaDate: "",
        nationality:"",
        secondIDType: 0,
        secondIDCard: '',
        NationalityDetail: '',
        NationalityCode: '',
        NationalityThreeCode: ''
    });

    let _selectPassengers = []

    if(realNameAdultCount > 0) {
        for(let i = 1; i <= realNameAdultCount; i++){
            _selectPassengers.push(passengerInfoContent(1, seat.SeatPrice))
        }
    }
    if(realNameChildCount > 0) {
        for(let i = 1; i <= realNameChildCount; i++){
            _selectPassengers.push(passengerInfoContent(2, seat.ChildSeatPrice))
        }
    }
    if(realNameStudentCount > 0) {
        for(let i = 1; i <= realNameStudentCount; i++){
            _selectPassengers.push(passengerInfoContent(3, seat.StudentPrice))
        }
    }
    if(realNameOldCount > 0) {
        for(let i = 1; i <= realNameOldCount; i++){
            _selectPassengers.push(passengerInfoContent(4, seat.OldSeatPrice))
        }
    }

    return _selectPassengers

  },

  
  /**
   * 校验航班号是否合法
   * @param {String} flightNumber 航班号
   * @returns {Boolean} 是否合法
   */
  validateFlightNumber: function (flightNumber) {
    const regEn = /[`~!@#$%^&*()_+<>?:"{},.\/;'[\]]/im
    const regCn = /[·！#￥（——）：；“”‘、，|《。》？、【】[\]]/im
    const regSpace = /\s+/g
    let isValid = true
    // 含有特殊字符
    if (regEn.test(flightNumber) || regCn.test(flightNumber) || regSpace.test(flightNumber)) {
        isValid = false
    }
    return isValid
  },

  getReserRule: function(params) {
    return getReserRuleApi(params)
  },
  // 提交订单
  submitOrder() {
    const self = this;
    // TODO 下单验证及提交
    this.setData({
      isPriceLayoutOpened: false
    })
    const { 
      passengers,
      currentSeat,
      phoneNumber, 
      emailStr, 

      carInsuranceInfo,
      currentCarIns,
      currentCar,

      nonRealNameConf,
      realNameAdultCount,
      realNameChildCount,
      realNameStudentCount,
      realNameOldCount,

      nonRealCertIndex,
      realNameConcatName,
      realNameCertNo,

      reservationRule,
      isAlterNativeTimeOpen,
      isCarSelected,
      carCode,

      isReductionOpen,
      isInvoiceOpen,
      isApproveChecked,
      passengerTypeConf,
      apiConnectTimeValid, // 接驳是否验证通过
      airLineName,
      vehicleRadioValue,
      truckInfo,


      startLine,
      lineConfig,
      returnVoyage,
      seatReturn,
      orderAmount, 
      support,
      isRoundTrip,
      airLineDepartureDate,
      airLineDepartureTime,
      flightNumber
    } = this.data;

    const currentVoyage = Object.assign({}, startLine, lineConfig)

    const selectedPassengers = this._selectedPasssengers(passengers)

    const {allPass, adults, children, senior, student, citizenAdults, citizenChildren} = this.passengerCategories({
        realNameAdultCount,
        realNameChildCount,
        realNameStudentCount,
        realNameOldCount,
        passengers: selectedPassengers, seat: currentSeat, isRealSys: currentVoyage.IsRealName})
    
          
    // 订单相关 start =========================
    
    //构造订单  oOCyauGAH82mE6NpRSElyt5b3GHk
    
    const openId = wx.getStorageSync(STORAGE_KEY.openId)
    const unionId = wx.getStorageSync(STORAGE_KEY.unionId)
    const memberId = wx.getStorageSync(STORAGE_KEY.memberId)
    const wxrefid = '512810788'
    let orderParams = {
        OpenId: openId,

        MemberId: memberId,
        unionId: unionId,
        SOWallet: 0,
        WxAppletType: 0,

        VersionType: 'txcxApplet',

        PassengersInfo: [],
        VehicleInfo: [],
        // 航线信息
        voyageId: currentVoyage.VoyageId, //航线ID
        Departure: currentVoyage.DepartCity, //出发城市
        Destination: currentVoyage.ArriveCity, //到达城市
        DeparturePort: currentVoyage.DepartPort, //出发港口
        ArrivePort: currentVoyage.ArrivePort, //到达港口
        DepartureTime: currentVoyage.DepartDateTime, //出发时间
        arriveTime: currentVoyage.ArriveDateTime, //到达时间
        LineCode: currentVoyage.LineCode, //航线编码
        LineId: currentVoyage.LineId, //港口航线iD
        ShipCode: currentVoyage.ShipCode, //船舶编码
        shipName: currentVoyage.ShipName, //船名
        // 保险信息
        SupplierId: currentVoyage.SupplierId, //供应商ID

        insuranceId: 0, //保险ID
        insuranceAmount: 0, //保险金额
        TravelInsuranceId: 0,
        TravelInsuranceAmount: 0,
        NonRealNameInsuranceId: 0,
        NonRealNameInsuranceAmount: 0,

        IsReserveOrder: 0,

        ContactName: '',
        ContactIdType: 0,
        ContactIdCard: '',

        SouthKoreaPhone: '',
        SouthKoreaAddress: '',

        currencyType: currentSeat.CurrencyType || 0,
        currencyTicketPrice: currentSeat.TotalCurrencyPrice || 0,
        currencyChildTicketPrice: currentSeat.TotalChildCurrencyPrice || 0,
        oldCurrencyTicketPrice: currentSeat.TotalOldCurrencyPrice || 0,

        SeatName: currentSeat.DisplayName,
        SeatId: currentSeat.SeatId,
        ContactNo: phoneNumber,
        Mail: emailStr,
        wxAppScene: 0,
        IsSerialVoyage: currentVoyage.IsSerialVoyage? 1: 0,
        GroupTicketPerferentialAmout: 0,
        // 票价信息
        TicketPrice: adults.price, //成人票单价
        childTicketPrice: children.price, //儿童票单价
        studentTicketPrice: student.price,
        oldTicketPrice: senior.price,

        TicketCount: allPass.count, //票总数
        childTicketCount: addNum(children.count, citizenChildren.count), //儿童票数量
        studentTicketCount: student.count,
        oldTicketCount: senior.count,

        activityId: '0', //折扣活动ID
        discountPrice: 0, //折扣金额
        TicketAmount: orderAmount, //票总价
        LocalCity: '',
        LocalProvince: '',

        TicketMaxAmount: 0,
        AlternativeCabins: [],
        AlternativeVoyages: [],

        RefId: wxrefid
    };

    try {
      setEvent('订单填写页', 'DD09', `^渠道refid:${wxrefid}^订单类型:船票^港口航线:${currentVoyage.DepartPort}-${currentVoyage.ArrivePort}^航线名称:${currentVoyage.DepartCity}-${currentVoyage.ArriveCity}^发船时间:${currentVoyage.DepartDateTime}^`)
    } catch(err) {
      console.log('DD09:', err)
    }

    if (selectedPassengers.length > lineConfig.OrderCountLimit) {
      wx.showModal({
        title: '温馨提示',
        content: `每个订单最多只能预定${lineConfig.OrderCountLimit}张票`
      })
      return 
    }
    // 校验
    if(passengers.length <=0 && selectedPassengers.length <= 0) {
      wx.showModal({
        title: '温馨提示',
        content: '请添加乘船人',
        showCancel: true,
        cancelText: '取消',
        confirmText: '立即添加',
        confirmColor: '#00c777',
        cancelColor: '#666666',
        success: function (res) {
          if (res.confirm) {
            self.goPassengersPage()
            setEvent('订单填写页', 'DD55', `^无常旅^`)
          } 
          else {
            setEvent('订单填写页', 'DD56', '')
          }
        }
      })
      return 
    }
    
    if (selectedPassengers.length < lineConfig.PersonMinCount) {
      wx.showModal({
        title: '温馨提示',
        content: `单笔订单最少需要添加${lineConfig.PersonMinCount}位乘客，请继续添加`,
        showCancel: true,
        cancelText: '取消',
        confirmText: '立即添加',
        confirmColor: '#00c777',
        cancelColor: '#666666',
        success: function (res) {
          if (res.confirm) {
            self.goPassengersPage()
          } 
        }
      })
      return 
    }

    if(adults.count <=0 && senior.count <= 0 && student.count <= 0 && citizenAdults.count <= 0) {
        wx.showModal({
          title: '温馨提示',
          content: '至少要一位成人'
        })
        return
    }

    if (currentVoyage.MaxCarryChildNum && !this.validateChildNumLimit(allPass,children, citizenChildren)) {
        wx.showModal({
          title: '温馨提示',
          content: '一名乘客仅可携带' + currentVoyage.MaxCarryChildNum + '名儿童，订单超过携带儿童数量限制，请重新选择乘客',
        })
        return;
    }

    if(currentVoyage.IsNeedEmail) {
        
        // 校验手机号
        if(!SHIP_REG.EMAIL.test(emailStr)) {
            wx.showToast({
                title: '请输入正确邮箱',
                icon: 'none',
                duration: 2000
            })
            self.setData({
              focusEle: 'email'
            })
            return;
        }
            
        wx.setStorageSync(STORAGE_KEY.email, emailStr)
    }

    if(currentVoyage.IsNeedMobileNo) {
        if(!phoneNumber) {
            asyncToast({
                title: '请输入手机号',
                icon: 'none',
                duration: 2000
            })
            self.setData({
              focusEle: 'phoneNumber'
            })
            return;
        }

        // 校验手机号
        if(!SHIP_REG.MOBILE.test(phoneNumber)) {
            wx.showToast({
                title: '请输入正确手机号',
                icon: 'none',
                duration: 2000
            })
            self.setData({
              focusEle: 'phoneNumber'
            })
            return;
        }

        // 保存车牌号、手机号，邮箱
        wx.setStorageSync(STORAGE_KEY.mobile, phoneNumber)
    }
    

    // 车辆上船 车辆类型、车牌号码 车辆保险
    if(isCarSelected) {
        const _carCodeNo = carCode.join('')
        if(!SHIP_REG.CAR_NO.test(_carCodeNo)) {
            wx.showToast({
                title: '请输入正确车牌号',
                icon: 'none',
                duration: 2000
            })
            return;
        }
            
        wx.setStorageSync(STORAGE_KEY.carLicense, carCode)
        

    }

    // 备选校验

    // 非实名制
    if(!currentVoyage.IsRealName){
        const ticketCount = addNum(realNameAdultCount, realNameChildCount, realNameStudentCount, realNameOldCount)
        let countParam = {
            realNameAdultCount: adults.count,
            realNameChildCount: children.count,
            realNameStudentCount: student.count,
            realNameOldCount: senior.count
        }
        if (ticketCount > currentSeat.TicketLeft) {
            wx.showToast({
                title: `余票数不足，当前余票数${currentSeat.TicketLeft}张`,
                icon: 'none',
                duration: 2000
            })
            return;
        }
        
        if(nonRealNameConf && nonRealNameConf.IsNeedContactName) {
            if(!realNameConcatName) {
                wx.showToast({
                    title: `请输入联系人`,
                    icon: 'none',
                    duration: 2000
                })
                return
            }
            countParam.name = realNameConcatName

            orderParams.ContactName = realNameConcatName; //联系人姓名
        }

        const realNameCert = nonRealNameConf.Certs[nonRealCertIndex]
        if(nonRealNameConf && nonRealNameConf.IsNeedContactCert && (realNameCert || realNameCertNo)) {
            if(!realNameCertNo) {
                wx.showToast({
                    title: `请输入证件号`,
                    icon: 'none',
                    duration: 2000
                })
                return
            }

            // 证件校验
            
            if(!CERT_REG[realNameCert.CertValue].test(realNameCertNo)) {
                wx.showToast({
                    title: `请输入有效证件号`,
                    icon: 'none',
                    duration: 2000
                })
                return
            }

            countParam.certType = realNameCert.CertValue
            countParam.certNo = realNameCertNo
            
            orderParams.ContactIdType = realNameCert.CertValue
            orderParams.ContactIdCard = realNameCertNo
        }

        const __selectedPassengers = self.setNoRealNamePassengers(currentSeat, countParam)

        orderParams.TicketAmount = orderAmount
        orderParams.PassengersInfo = __selectedPassengers
        orderParams.TicketCount = ticketCount
        orderParams.childTicketCount = realNameChildCount;
        orderParams.oldTicketCount = realNameOldCount;
        orderParams.studentTicketCount = realNameStudentCount;

        // orderParams.ContactIdType = realNameCert;//联系人证件类型
        // orderParams.ContactIdCard = realNameCertNo; //联系人证件号码
        orderParams.ContactNo = phoneNumber;//联系人手机号码
        orderParams.Mail = emailStr;

        // TODO: 韩国手机 韩国地址 韩国邮箱

    } else {
        let orderPassengers = []
        let carryChildMsg = ''
        let carryChildSubMsg = ''
        // 下单常旅
        selectedPassengers.map(item => {

            let firstSelCert = null, secondSelCert = null, passportDate = '';
            if(item.validFirstCert && item.validFirstCert.certNo) {
                firstSelCert = item.validFirstCert
                if(firstSelCert.certType === 2) {
                    passportDate = firstSelCert.certActiveTime
                }
            }
            if(item.validSecondCert && item.validSecondCert.certNo) {
                secondSelCert = item.validSecondCert
                if(secondSelCert.certType === 2) {
                    passportDate = secondSelCert.certActiveTime
                }
            }

            // TODO: 这里判断有问题
            if(!firstSelCert && !secondSelCert) {
                wx.showToast({
                    title: '乘客信息有误',
                    icon: 'none',
                    duration: 2000
                })
                return
            }

            // 乘客类型
            // item.linkerType 参数 0: 成人, 1: 儿童, 2: 学生, 3: 长者 22 北海市民成人  24 北海市民儿童
            // 下单参数中  passengerType    1: 成人, 2: 儿童, 3: 学生, 4: 长者
            let _userType = 1 // 默认成人
            let _seatPrice = 0
            switch(Number(item.linkerType)) {
                case 0:
                    _userType = 1
                    _seatPrice = currentSeat.SeatPrice
                    break;
                case 1:
                    _userType = 2
                    _seatPrice = currentSeat.ChildSeatPrice
                    break;
                case 2:
                    _userType = 3
                    _seatPrice = currentSeat.StudentPrice
                    break;
                case 3:
                    _userType = 4
                    _seatPrice = currentSeat.OldSeatPrice
                    break;
                case 22:
                    _userType = 22
                    _seatPrice = currentSeat.CitizenSeatPrice
                    break;
                case 24:
                    _userType = 24
                    _seatPrice = currentSeat.CitizenChildSeatPrice
                    break;
            }
            let passengerItem = {
                Name: item.fullname,
                IdCard: firstSelCert.certNo,
                IdType: firstSelCert.certType,
                MobileNo: item.mobile || '',
                birthDay: item.birthday || '',
                passportDate: passportDate,
                visaDate: item.visaDate || "",
                nationality: item.nationality || "",
                Sex: item.sex == 0 ? 1 : 0,
                passengerType: _userType,
                SeatType: currentSeat.SeatType,
                SeatName: currentSeat.DisplayName,
                TicketPrice: _seatPrice + "",
                SeatId: currentSeat.SeatId,
                UserType: _userType,
                NationalityDetail: item.nationalityDetail || '',
                NationalityCode: item.nationalCode || '',
                NationalityThreeCode: item.nationalityThreeCode || '',
                issuedate: item.issuedate || '',

                visaType: item.visaType,
                visaNum: item.visaNum,
                stayDays: item.stayDays,
            }


            if(secondSelCert) {
                passengerItem.secondIDType = secondSelCert.certType;
                passengerItem.secondIDCard = secondSelCert.certNo;
            }

            // 选中携童 需要校验 证件或姓名
            if(item.showCarryForm) {
                
                if(currentVoyage.IsNeedCarryChildCert) {    
                    let carryChildBirthday = ''
                    item.carryChildName = item.carryChildName || ''
                    if(!item.carryChildName) {
                        // 请输入儿童姓名 
                        carryChildMsg = '请输入儿童姓名'
                    }else if (item.carryChildName.length <= 1 || (!new RegExp("^([\u4E00-\uFA29]|[\uE7C7-\uE7F3]|[·])*$").test(item.carryChildName) && !new RegExp("^([a-zA-Z]|[·])*$").test(item.carryChildName))) {
                        carryChildMsg = '请输入正确的姓名（都为中文或英文）'
                        carryChildSubMsg = '不能只输入一个字'
                    }else if(!CERT_REG[1].test(item.carryChildCert)) {
                        // 请输入儿童证件
                        carryChildMsg = '请输入正确的儿童身份证号'
                        carryChildSubMsg = ''
                    } else {
                        // 通过证件获取年龄 进行比较
                        const certInfo = getBirthAndSex(item.carryChildCert)
                        carryChildBirthday = certInfo.birthDay

                        if(passengerTypeConf && passengerTypeConf.CarryAge) {
                            const carryChildAge = getAgeInt(carryChildBirthday)
                            if(passengerTypeConf.CarryAge.MaxVal < carryChildAge || carryChildAge < passengerTypeConf.CarryAge.MinVal ) {
                                carryChildMsg = `添加的携童${item.carryChildName}不满足携童条件`
                                carryChildSubMsg = ''
                            }
                        }

                    }
                    
                    // 校验携童是否满足 条件
                    passengerItem.carrychildInfo = {
                        IsNeedCert: 1,
                        CName: item.carryChildName,
                        Sex: 0,
                        BirthDay: carryChildBirthday,
                        FirstCertType: '1',
                        FirstCertNo: item.carryChildCert
                    }
                    
                } else {
                    passengerItem.carrychildInfo = {
                        IsNeedCert: 0
                    }
                }

            }
            // 往返票
            if(isRoundTrip && seatReturn) {
                passengerItem.ReturnSeatType = seatReturn.SeatType;
                passengerItem.ReturnSeatId = seatReturn.SeatId;
                passengerItem.ReturnSeatName = seatReturn.DisplayName;
                let returnTicketPrice = 0
                switch(item.linkerType) {
                    case 0:
                        returnTicketPrice = seatReturn.SeatPrice
                        break;
                    case 1:
                        returnTicketPrice = seatReturn.ChildSeatPrice
                        break;
                    case 2:
                        returnTicketPrice = seatReturn.StudentPrice
                        break;
                    case 3:
                        returnTicketPrice = seatReturn.OldSeatPrice
                        break;
                }
                passengerItem.ReturnTicketPrice = returnTicketPrice;
            }
            orderPassengers.push(passengerItem)
        })

        if(carryChildMsg) {
            wx.hideLoading()
            self.showShipModal({
                title: '温馨提示',
                content: carryChildMsg,
                subContent: carryChildSubMsg,
                cancel: '',
                confirm: '知道了'
            },()=>{

            })

            return;
        }

        // 女士舱位

        if(currentVoyage.isForFemale) {
                
            const malePassengers = orderPassengers.filter(item => item.Sex === 0)
            const childPassengers = orderPassengers.filter(item => item.Sex === 0)
            if(malePassengers.length > 0) {
                wx.showToast({
                    title: '该舱位为女士专属舱位，男士无法购买，请重新选择乘客',
                    icon: 'none',
                    duration: 2000
                })

                return;
            }
            if(childPassengers.length > 0) {
                wx.showToast({
                    title: '女士专属舱位不支持儿童票，请重新选择乘客',
                    icon: 'none',
                    duration: 2000
                })
                return;
            }

        }

        // 往返票下单参数
        if(isRoundTrip) {
            orderParams.IsRoundTripNew = 1
            orderParams.ReturnShipCode = returnVoyage.ShipCode
            orderParams.ReturnDate = returnVoyage.DepartDateTime
            orderParams.returnLineId = returnVoyage.LineId
        }

        orderParams.PassengersInfo = orderPassengers
        orderParams.TicketAmount = orderAmount

        // 联系人 为第一个成人
        const firstAdultPassenger = orderPassengers.filter(item => item.passengerType !== 2)[0]
        orderParams.ContactName = firstAdultPassenger.Name
        orderParams.ContactIdType = firstAdultPassenger.IdType
        orderParams.ContactIdCard = firstAdultPassenger.IdCard
    

    } 
    
    // 发票信息校验
    if(isInvoiceOpen) {
        const invoiceErrMsg = this.checkInvoceForm()
        if(invoiceErrMsg.length > 0) {
            wx.showToast({
                title: invoiceErrMsg[0],
                icon: 'none',
                duration: 2000
            })
            return
        }
    }

    if(!isApproveChecked) {
        const { approveCates } = this.data
        let approveTxt = []
        approveCates.forEach((item) => {
            approveTxt.push(APPROVE_DESC[item])
        })
        
        this.showShipModal({
            title: '温馨提示',
            content: `同意 ${approveTxt.join('、')} 才能购票`,
            subContent: '',
            cancel: '',
            confirm: '确定'
        }, () => {
        })
        wx.hideLoading()
        return
    }

    // 预约票 
    if(currentVoyage.IsReseverVoyage && reservationRule) {
        orderParams.IsReserveOrder = 1;
        if(isAlterNativeTimeOpen) {
            orderParams.ReserveTimeSlot = reservationRule.AlternativeTime
        }
    }

    // IsRevenueOrder 是否从1.5页面过来

    // 备选舱位
    // 备选班次
    // 增值服务
    // 增值服务参数

    // 车辆上船
    const carOnShipObj = this.getCarOnShipParam({carInsurance: carInsuranceInfo, currCar: currentCar, currentCarIns: currentCarIns, open: isCarSelected, carCode,vehicleRadioValue, truckInfo})
    if(carOnShipObj.carOnShip && carOnShipObj.param) {
        orderParams.VehicleInfo = carOnShipObj.param.VehicleInfo
        if(carOnShipObj.param.VehiclePrice > 0) {
            orderParams.VehicleInsuranceConfigId = carOnShipObj.param.VehicleInsuranceConfigId
            orderParams.VehicleInsuranceId = carOnShipObj.param.VehicleInsuranceId
            orderParams.VehiclePrice = carOnShipObj.param.VehiclePrice
        }
    }
    
    if(support.airline && !apiConnectTimeValid) {
        if(!airLineName) {
            wx.showToast({
                title: '请选择航空公司',
                icon: 'none',
                duration: 2000
            })
            return
        }
        if(!airLineDepartureDate || !airLineDepartureTime) {
            wx.showToast({
                title: '请选择航班日期',
                icon: 'none',
                duration: 2000
            })
            return;
        }
        // 航班号必填
        if (!flightNumber) {
            wx.showToast({
                title: '请输入航班号',
                icon: 'none',
                duration: 2000
            })
            return;
        }
        // 校验航班号的合法性
        if (!this.validateFlightNumber(flightNumber)) {
            wx.showToast({
                title: '航班号不能包含特殊字符',
                icon: 'none',
                duration: 2000
            })
            return;
        }
        const takeOffDate = dayjs(`${airLineDepartureDate} ${airLineDepartureTime}`).format('YYYY-MM-DD H:mm')
              
        verifyConnectTimeApi({
            // LineCode: currentVoyage.LineCode,
            AirPortName: airLineName,
            LineId: currentVoyage.LineId,
            DepartureDateTime: currentVoyage.DepartDateTime,
            TakeOffDateTime: takeOffDate,
        }).then(res => {
            if(!res) {
                wx.showModal({
                  title: '温馨提示',
                  content: `为保证您有足够的时间赶上飞机，请选择更早时间的客船。`,
                  showCancel: false,
                  confirmText: '确定',
                  confirmColor: '#00c777'
                });
                return;
            }

            // 机场线下单参数
            // orderParams.DepartureTime = takeOffDate; //出发时间
            orderParams.airPortName = airLineName;
            orderParams.takeOffDateTime = takeOffDate;
            orderParams.AirFlightNo = flightNumber // 航班号
      
            this.createOrder(orderParams)
        })
        return;
    }

    this.setData({
        orderParams
    })
    this.createOrder(orderParams)
    // this.getPopupConfigHandle(orderParams)
  },

  createOrder: function(orderParams) {
    const that = this
    wx.showLoading({
      title: '正在处理',
      mask: true
    })

    createOrderApi({
      serviceName: "createshipordernew",
      params: JSON.stringify(orderParams)
    }).then(response => {
      if(!response || response.status !== 200) {
          return
      }
      if(!response.data || response.ResCode) {
          return
      }

      if(Number(response.data.ResCode)  !== 0 || !response.data.Body) {
        this.showWarnModalFunc(response.data)
        wx.hideLoading()
        return
      }

      const createRes = response.data.Body

      // 创单确认弹框 延迟处理
      that.delayCheckOrderList(orderParams, () => {
        that.pay(createRes)
      })


    })

  },
  
  pay: function(createRes) {
    const that = this
    const { totalAmount, serialId } = createRes
    this.setData({
      totalAmount,
      payargs: {
        fee: mulNum(totalAmount, 100),
        paymentArgs: {
          serialId
        }
      }
    }, () => {
      that.alertPayDialog()
    })
    // return new Promise((resolve, rejecet) => {
    //   resolve(null)
    // })
  },


  // 跳转订单详情页
  goOrderDetailPage: function({serialId}) {
    wx.redirectTo({
      url: `../order/index?serialId=${serialId}`
    })
  },

  
  /**
   * 展示下单失败弹框
   * @param {Any} createOrderResult 
   */
  showWarnModalFunc(createOrderResult){
    var self = this
    if (createOrderResult && createOrderResult.ResCode === 2000) { //下单失败
        // let linedetail = that.data.linedetail
        let desc = createOrderResult.ResDesc,
            title = "",
            confirmText = "我知道了",
            cancelText = '',
            showCancel = false,
            typeName = '其他异常'
        if(desc.indexOf(' ')>-1){
            let desc_split = desc.split(' ')
            desc = desc_split[1]
            title = desc_split[0]
        }
        switch (createOrderResult.APIErrorCode) {
            case '1':
                typeName = '证件问题'
                break;
            case '2':
                typeName = '重复单'
                confirmText = "预订返程"
                cancelText = '我知道了'
                showCancel = true
                break;
            case '3':
                typeName = '联系人证件问题'
                break;
            case '4':
                typeName = '航班异常'
                confirmText = '重新选择出发班次'
                break;
            case '5':
                typeName = '舱位/价格/余票异常'
                confirmText = '重新选择出发班次'
                break;
            default: 
                break;
        }
        self.setData({
            showWarnModal: true,
            errorCode: createOrderResult.APIErrorCode,
            warnModal: {
                title,
                desc,
                confirmText,
                cancelText,
                showCancel,
            }
        })
    } else {
        self.setData({
            showWarnModal: true,
            errorCode: '0',
            warnModal: {
                title:'',
                desc:createOrderResult.ResDesc,
                confirmText:'我知道了',
                cancelText:'',
                showCancel:false,
            }
        })
    }
  },

  onChangeAdult: function(e) {
    const that = this
    const val = e.detail
    this.setData({
      realNameAdultCount: val
    }, () => {
      that.priceCalculation()
    })
  },
  onChangeChild: function(e) {
    const that = this
    const val = e.detail
    this.setData({
      realNameChildCount: val
    }, () => {
      that.priceCalculation()
    })
  },
  onChangeStudent: function(e) {
    const that = this
    const val = e.detail
    this.setData({
      realNameStudentCount: val
    }, () => {
      that.priceCalculation()
    })
  },
  onChangeOld: function(e) {
    const that = this
    const val = e.detail
    this.setData({
      realNameOldCount: val
    }, () => {
      that.priceCalculation()
    })
  },


  
  // 儿童数量限制
  validateChildNumLimit(allPass, children, citizenChild) {
    const lineConfig = this.data.lineConfig
    let carrChildNum = lineConfig.MaxCarryChildNum,
        childCount = children.count,
        citizenChildCount = citizenChild.count,
        adultCount = allPass.count - childCount - citizenChildCount
    if (adultCount * carrChildNum >= childCount) {
        return true
    } else {
        return false
    }
  },



  /**
   * 创单确认弹框
   *
   * @param {*} callback
   * @memberof Index
   */
  delayCheckOrderList(params, callback) {
    const { startLine, lineConfig } = this.data;
    const currentVoyage = Object.assign({}, startLine, lineConfig)

    wx.hideLoading()
    // let list = _cloneDeep(checkOrderList)
    let allItems = 0
    let allItemsArr = []
    const vehicleInfo = params.VehicleInfo[0]
    let passengers = []
    params.PassengersInfo.map((item, index) => {
        if(item.Name && index > 2 && index < 10) {
            passengers.push(item.Name.replace(/-/g, ' ').trim())
        }
    })
    
    var ticketInfo = []
    if(params.IsRoundTripNew && params.IsRoundTripNew === 1) {
        ticketInfo = [{
            id: 11,
            done: false,
            round: '去程',
            value:  dayjs(params.DepartureTime).format('YYYY-MM-DD') + ' ' + WEEK_ENUM[dayjs(params.DepartureTime).day()] + ' ' + dayjs(params.DepartureTime).format('HH:mm')
        },{
            id: 12,
            done: false,
            round: '返程',
            value: dayjs(params.ReturnDate).format('YYYY-MM-DD') + ' ' + WEEK_ENUM[dayjs(params.ReturnDate).day()] + ' ' + dayjs(params.ReturnDate).format('HH:mm')
        },{
            id: 13,
            done: false,
            value: `${params.Departure}-${params.Destination}（往返）`
        },{
            id: 14,
            done: false,
            value: `${params.DeparturePort}-${params.ArrivePort}`
        },{
            id: 15,
            done: false,
            value: `${params.ArrivePort}-${params.DeparturePort}`
        }]
    } else {

        var aMPm = '上午 '
        var hours = dayjs(params.DepartureTime).hour()
        var minutes = dayjs(params.DepartureTime).minute()
        var seconds = dayjs(params.DepartureTime).second()
        if(hours > 11) {
            aMPm = '下午 '
            if(hours === 12 && minutes === 0 && seconds === 0) {
                aMPm = '中午 '
            }
        }
        var dateTitle = dayjs(params.DepartureTime).format('YYYY-MM-DD') + ' ' + WEEK_ENUM[dayjs(params.DepartureTime).day()]
        if(currentVoyage.IsSerialVoyage) {
            dateTitle = dateTitle + ' 流水班'
        } else {
            dateTitle = dateTitle + ' ' + aMPm + dayjs(params.DepartureTime).format('HH:mm')
        }

        ticketInfo = [{
            id: 11,
            done: false,
            value: dateTitle
        }, {
            id: 12,
            done: false,
            value: `${params.Departure}-${params.Destination}`
        },{
            id: 13,
            done: false,
            value: `${params.DeparturePort}-${params.ArrivePort}`
        }]
    }

    let checkOrderList = [{
        id: 1,
        title: '请核对您的船票信息',
        items: ticketInfo
    }]

    if(params.TicketOrderList && params.TicketOrderList.length > 0) {
        let ticketOrders = []
        params.TicketOrderList.forEach(item => {
            
            ticketOrders.push({
                id: item.StrategyId,
                done: false,
                value: item.StrategyName + ' ' + item.TicketName
            },{
                id: `${item.StrategyId}_date`,
                done: false,
                value: `${item.UseDate}  使用`
            })
        })
        checkOrderList.push({   
            id: 2,
            title: '请核对组合产品名称',
            items: ticketOrders
        })
    }

    if(params.PassengersInfo.length > 0 || vehicleInfo) {
        let itemList = []
        if(vehicleInfo) {
            itemList.push({
                id: 31,
                done: false,
                label: '车牌',
                value: vehicleInfo.NO
            })
        }
        
        if(currentVoyage.IsRealName) {
            const prefix = params.PassengersInfo.length > 10? `等${params.PassengersInfo.length}人`: ''
            params.PassengersInfo.forEach(function (passenger, passengerIndex) {
                if (passengerIndex < 3 && passenger.Name) {
                    itemList.push({
                        id: 32 + passengerIndex,
                        done: false,
                        label: passenger.Name.replace(/-/g, ' ').trim(),
                        subtit: (SHIP_CERT_TYPE[passenger.IdType] ? SHIP_CERT_TYPE[passenger.IdType] : '') + ':'
                            + (passenger.IdType == 1 ? mask(passenger.IdCard, 6, 14) : passenger.IdCard),
                    })
                }
            })
            if (passengers.length > 0) {
                itemList.push({
                    id: 35,
                    done: false,
                    label: passengers.join('、') + prefix,
                })
            }
        }
        let ployHaveIns = false

        if(itemList.length > 0) {
            let passengerTitle = '请核对乘船人信息'
            if (params.insuranceId || 
                params.TravelInsuranceId || 
                params.NonRealNameInsuranceId ||
                params.RuleId ||
                params.VehicleInsuranceId || 
                (params.PreferredServicePloyId && ployHaveIns))
            {
                passengerTitle += '/投保人信息'
            }
            checkOrderList.push({
                id: 3,
                title: passengerTitle,
                items: itemList
            })
        }
    }

    checkOrderList.forEach(item => {
        item.items.forEach(sub => {
            allItems ++
            allItemsArr.push(sub)
        })
    })
    const itemStamp = Math.ceil(CHECK_ORDERLIST_SECONDS / allItems)
    this.setData({
        isCheckOrderListOpen: true
    })

    this.timingLoading(checkOrderList, allItemsArr, itemStamp, callback)
  },

  
  /**
   * 创单确认弹框 定时跑 任务 打钩
   *
   * @param {*} checkOrderList
   * @param {*} list
   * @param {*} itemStamp
   * @param {*} callback
   * @memberof Index
   */
  timingLoading: function(checkOrderList, list, itemStamp, callback) {
    const that = this
    const listTmp = Object.assign([], checkOrderList)
      
    // loading 的items数
      list.forEach((it, index) => {
          const timeCount = itemStamp * (index + 1)
          let timer = setTimeout(() => {
            listTmp.forEach(item => {
                  item.items.forEach(sub => {

                    // 通过id筛选 进行状态变更
                      if(it.id === sub.id) {
                          sub.done = true
                      }
                  })
              })
              if(timeCount >= CHECK_ORDERLIST_SECONDS) {
                  let doneTimer = setTimeout(() => {
                    that.setData({
                        isCheckOrderListOpen: false
                    })
                    clearTimeout(doneTimer)
                    callback && callback()
                  }, 500)
              }
              clearTimeout(timer)
        
              that.setData({
                checkOrderList: listTmp
            })
          }, timeCount)

      })
  },


  
  /**
   * 获取支持价格的详情列表
   * @param {Array} priceDesc 价格列表
   * @param {Any} passengerTypeConf 乘客类型描述
   * @returns {Array}
   */
  getPriceDetailList (priceDesc, voyage, passengerTypeConf) {
    if (!priceDesc) {
        return []
    }

    let detailList = []
    priceDesc.forEach(item => {
      if(item) {
        const descArr = item.split('/')
        const element = {
            price: descArr[0],
            type: descArr[1],
            detail: ''
        }
        if (item.includes('成人')) {

        } else if (item.includes('儿童')) {
            if (passengerTypeConf && passengerTypeConf.ChildAge) {
                element.detail += `年龄${passengerTypeConf.ChildAge.Content}${passengerTypeConf.ChildAge.SupplementaryContent}`
            }
            if (passengerTypeConf && passengerTypeConf.ChildHeight) {
                if (element.detail) {
                    element.detail += '，'
                }
                element.detail += `身高${passengerTypeConf.ChildHeight.Content}${passengerTypeConf.ChildHeight.SupplementaryContent}`
            }
        } else if (item.includes('携童')) {
            if (passengerTypeConf && passengerTypeConf.CarryAge) {
                element.detail += `年龄${passengerTypeConf.CarryAge.Content}${passengerTypeConf.CarryAge.SupplementaryContent}`
            }
            if (passengerTypeConf && passengerTypeConf.CarryHeight) {
                if (element.detail) {
                    element.detail += '，'
                }
                element.detail += `身高${passengerTypeConf.CarryHeight.Content}${passengerTypeConf.CarryHeight.SupplementaryContent}`
            }
        } else if (item.includes('长者')) {
            if (passengerTypeConf && passengerTypeConf.OldAge) {
                element.detail += `年龄${passengerTypeConf.OldAge.Content}${passengerTypeConf.OldAge.SupplementaryContent}`
            }
        } else if (item.includes('服务费')) {
            element.detail = voyage.Discount?'服务费包含技术接入费，支付手续费，短信费，如产生退票服务费部分可退':'含技术接入费，支付手续费等费用'
        }
        // return element
        detailList.push(element)
      }
    })
    return detailList
  },


  // 价格计算
  priceCalculation: function() {
    const { 
      startLine, 
      lineConfig, 
      passengers, 
      currentSeat,

      support,
      isRoundTrip,

      realNameAdultCount,
      realNameChildCount,
      realNameStudentCount,
      realNameOldCount,

      carInsuranceInfo,
      currentCar,
      currentCarIns,
      isCarSelected,
      carCode,
      truckInfo,
      vehicleRadioValue, // FIXME: 这啥
    } = this.data
    
    const currentVoyage = Object.assign({}, startLine, lineConfig)

    const selectedPassengers = this._selectedPasssengers(passengers)
    let priceList = []
    let orderAmount = 0

    const roundTxt = isRoundTrip? '往返票': ''

    // 常旅  新增、删除
    const {allPass, adults, children, senior, student, citizenAdults, citizenChildren} = this.passengerCategories({
        
      realNameAdultCount,
      realNameChildCount,
      realNameStudentCount,
      realNameOldCount,
      passengers: selectedPassengers, seat: currentSeat, isRealSys: currentVoyage.IsRealName})

    if (adults.count > 0) {
      priceList.push({
        hidden: false,
        type: '成人票' + roundTxt,
        price: adults.price,
        count: adults.count
      })
    }

    if(currentSeat.CitizenSeatPrice > 0 && citizenAdults.count > 0) {
      priceList.push({
        hidden: false,
        type: '市民成人票',
        price: citizenAdults.price,
        count: citizenAdults.count
      })
    }

    if(currentSeat.CitizenChildSeatPrice > 0 && citizenChildren.count > 0) {
        priceList.push({
            hidden: false,
            type: '市民儿童票',
            price: citizenChildren.price,
            count: citizenChildren.count
        })
    }

    if (support.children && children.count > 0) {

        priceList.push({
            hidden: false,
            type: '儿童票' + roundTxt,
            price: children.price,
            count: children.count
        })
    }
    if (support.student && student.count > 0) {
        priceList.push({
            hidden: false,
            type: '学生票' + roundTxt,
            price: student.price,
            count: student.count
        })
    }
    if (support.old && senior.count > 0) {
        priceList.push({
            hidden: false,
            type: '长者票' + roundTxt,
            price: senior.price,
            count: senior.count
        })
    }



    // 车辆上船
    const carOnShipObj = this.getCarOnShipParam({carInsurance: carInsuranceInfo, currCar: currentCar, currentCarIns: currentCarIns, open: isCarSelected, carCode,vehicleRadioValue, truckInfo})
    if(carOnShipObj.carOnShip) {
      priceList = priceList.concat(carOnShipObj.priceListTmp)

      // 车辆保险
      if(carOnShipObj.param && carOnShipObj.param.VehiclePrice > 0) {
          _approveCates.push(4)
      }
    }


    // 各种航线服务费  = 供应商航线服务费 + 同程航线服务费 + 优惠服务费
    let serviceFee = addNum(currentVoyage.LineServiceFee || 0, currentVoyage.TCLineServiceFee || 0) * allPass.count
    if(serviceFee > 0) {
      priceList.push({
          hidden: true,
          type: `航线服务费`,
          price: serviceFee,
          count: 1
      })
    }
    if(currentVoyage.PierCleaningFee > 0) {
      priceList.push({
          hidden: false,
          type: `码头清洁费`,
          price: currentVoyage.PierCleaningFee,
          count: allPass.count
      })
    }

    if(currentVoyage.PortServiceFee > 0) {
        priceList.push({
            hidden: false,
            type: `港口服务费`,
            price: currentVoyage.PortServiceFee,
            count: allPass.count
        })
    }

    if(currentVoyage.AdditionalFuelFee > 0) {
        priceList.push({
            hidden: false,
            type: `燃油附加费`,
            price: currentVoyage.AdditionalFuelFee,
            count: allPass.count
        })
    }


    // 计算订单金额
    if (priceList && priceList.length > 0) {
      const allItemPrice = priceList.map(item => mulNum(item.price, item.count))
      orderAmount = allItemPrice.reduce((prev, cur) => {
          return addNum(prev, cur)
      }, 0)
    }
    console.log("selectedPassengers: ", selectedPassengers)

    adults, children, senior, student, citizenAdults, citizenChildren

    const AllAdultPrice = addNum(adults.price, adults.count)
    const AllChildrenPrice = addNum(children.price, children.count)
    const AllSeniorPrice = addNum(senior.price, senior.count)
    const AllStudentPrice = addNum(student.price, student.count)
    const AllCitizenAdultsPrice = addNum(citizenAdults.price, citizenAdults.count)
    const AllCitizenChildrenPrice = addNum(citizenChildren.price, citizenChildren.count)
    const shipVehiclePrice = currentCar.vehicleTicketPrice || 0

    const allTicketPrice = addNum(AllAdultPrice, AllChildrenPrice, AllSeniorPrice, AllStudentPrice, AllCitizenAdultsPrice, AllCitizenChildrenPrice, shipVehiclePrice)
    const isOnlyTicket = this.isOnlyTicket(orderAmount, allTicketPrice)
    // 更新发票副标题
    let invoiceSubtitle = ''
    if (this.data.supplierInfo) {
        invoiceSubtitle = '出票成功后至订单详情开具，安心购票'
        switch (this.data.supplierInfo.InvocingType) { 
            case 0:
                if (isOnlyTicket) {
                    invoiceSubtitle = '纸质船票本身为报销凭证'
                }
                break; 
            default:
                
        }
    }


    this.setData({
      priceList,
      orderAmount,
      selectedPassengers,
      invoiceSubtitle
    })
    
  },


  /**
   * 是否未购买辅营或服务费（只购买船票和车辆上船）
   * @param {Number} totalPrice 
   * @param {Number} ticketPrice 
   * @returns {Boolean}
   */
  isOnlyTicket: function (totalPrice, ticketPrice) {
    var totalPriceCopy = totalPrice || 0
    var ticketPriceCopy = ticketPrice || 0
    return totalPriceCopy - ticketPriceCopy === 0
  },

  onPriceList: function() {
    const priceList = this.data.priceList

    const vstValue = this.data.vstValue
    setEvent('订单填写页', 'DD08', vstValue)

    if(!priceList || priceList <= 0) return
    const isPriceLayoutOpened = this.data.isPriceLayoutOpened
    this.setData({
      isPriceLayoutOpened: !isPriceLayoutOpened
    })
  },
  closePriceLayout: function() {
    this.setData({
      isPriceLayoutOpened: false
    })
  },


  openTicketDetailWindow: function() {
    const isTicketDetailOpened = this.data.isTicketDetailOpened
    this.setData({
      isTicketDetailOpened: !isTicketDetailOpened
    })
  },

  toggleSlideHandler: function() {
    const remindChecked = this.data.remindChecked
    this.setData({
      remindChecked: !remindChecked
    })

    const vstValue = this.data.vstValue
    setEvent('订单填写页', 'DD07', vstValue)
  },


  handlePayClose: function() {},
  handlePayCancel: function() {
    this.closePayDialog()
    const { paymentArgs } = this.data.payargs
    this.goOrderDetailPage(paymentArgs)
  },
  handlePayConfirm: function() {
    this.closePayDialog()
  },

  // 支付成功的回调接口
  paymentSuccess: function(e) {
    const { paymentArgs } = this.data.payargs
    this.goOrderDetailPage(paymentArgs)
    // e.detail.extraData.timeStamp // 用 extraData 传递数据，详见下面功能页函数代码
  },

  // 支付失败的回调接口
  paymentFailed: function(e) {
    const { paymentArgs } = this.data.payargs
    this.goOrderDetailPage(paymentArgs)
  },

  alertPayDialog: function() {
    this.setData({
      isOpenedPayModal: true
    })
  },
  closePayDialog: function() {
    this.setData({
      isOpenedPayModal: false,
      // totalAmount: 0,
      // payargs: {
      //   fee: 0,
      //   paymentArgs: {
      //     serialId: ''
      //   }
      // }
    })
  },

  onCancelWarnModal: function() {
    const self = this;
    self.setData({
        showWarnModal: false
    })
  },

  onConfirmWarnModal: function() {
    const self = this;
    self.setData({
        showWarnModal: false
    })
    let navigateUrl = '',currentVoyage = self.data.startLine
    let departDateTime = currentVoyage.DepartDateTime
    departDateTime = departDateTime.split(' ')[0]
    switch (self.data.errorCode) {
        case '2':
                  
          // 返回首页重定向到返程列表
          navigateUrl = `../list/index?start=${departDateTime}&end=&from=${currentVoyage.ArriveCity}&to=${currentVoyage.DepartCity}&cityLineId=${currentVoyage.CityLineId || 0}`
          // navigateUrl = `/Views/List/Index?start=${departDateTime}&from=${currentVoyage.ArriveCity}&to=${currentVoyage.DepartCity}`
          break;
        case '4':
            // 返回首页重定向到列表
            navigateUrl = `../list/index?start=${departDateTime}&end=&from=${currentVoyage.DepartCity}&to=${currentVoyage.ArriveCity}&cityLineId=${currentVoyage.CityLineId || 0}`
            // navigateUrl = `/Views/List/Index?start=${departDateTime}&from=${currentVoyage.DepartCity}&to=${currentVoyage.ArriveCity}`
            break;
        case '5':
            // 返回首页重定向到列表 并只展示当前航线的班次
            navigateUrl = `../list/index?start=${departDateTime}&end=&from=${currentVoyage.DepartCity}&to=${currentVoyage.ArriveCity}&portLineId=${currentVoyage.LineId}`
            // navigateUrl = `/Views/List/Index?start=${departDateTime}&from=${currentVoyage.DepartCity}&to=${currentVoyage.ArriveCity}&portLineId=${currentVoyage.LineId}`
            break;
        default:
            break;
    }
    wx.redirectTo({
        url: navigateUrl
    })
  },

  onApproveTip: function(e) {
    const item = e.currentTarget.dataset.item
    
    let title = '', content = ''
    switch(item) {
        case 1:
            this.onServiceNotice({});
            break;
        case 2:
            title = '船票代订服务协议'
            content = SHIP_SERVICE_AGREEMENT_HTML
            break;
        default:
          break;
    }

    if(content && title && item !== 2) {
        this.setState({
            isDialogInsOpen: true,
            dialogContent: content,
            dialogTitle: title
        })
    }
    

  },

  onClickNoticeBar: function() {
    
    const lineConfig = this.data.lineConfig
    if(!lineConfig.OrderNotice) return
    wx.showModal({
      title: '公告',
      content: lineConfig.OrderNotice,
      showCancel: false,
      confirmText: '确定',
      confirmColor: '#00c777'
    });
  },

  alterNativeSwitchChange: function(e) {
    this.setData({
      isAlterNativeTimeOpen: e.detail.value
    })
  },

  closeReserveTicketNotice: function() {
    this.setData({
      showReserveNotice: false
    })
  },

  bindCertChange: function(e) {
    this.setData({
      nonRealCertIndex: e.detail.value
    })
  },

  
  getInvoiceDetail: function(startLine) {
    const that = this
    const { SupplierId } = startLine
    getInvoiceDetailNewApi({
      supplierId: SupplierId,
      serialId: ''
    }).then(response => {
        
    
        if(!response || response.status !== 200) {
        return
      }
      if(!response.data || !response.data.isSuccess) {
          return
      }
      const result = response.data.data

    //   FIXME: 发票test
      // result.SupplierInfo.InvocingType = 1
      // result.SupplierInfo.OfflineInvoiceType = 2
      // result.InvoicingInfo.InvoiceStatus = 0
 
      that.setData({
          supplierInfo: result.SupplierInfo
      })
    
     
    })
  },

})